//
//  MarqueeView.m
//  Nidalee
//
//  Created by 李康 on 2020/12/1.
//  Copyright © 2020 李康. All rights reserved.
//

#import "MarqueeView.h"
#import <Masonry/Masonry.h>
#import "BaseMacroConfig.h"

@interface MarqueeView ()<CAAnimationDelegate> {
    NSTimeInterval _timeInterval;//时间
}
//警示 view
@property (nonatomic, strong) UIImageView *tipImv;
//跑马灯 view
@property (nonatomic, strong) UIView *marqueeView;
//关闭按钮
@property (nonatomic, strong) UIButton *closeBtn;
//原 label
@property (nonatomic, strong) UILabel *marqueeLb;

@end


@implementation MarqueeView

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorWithRed:0xec/255.0 green:0xf5/255.0 blue:0xff/255.0 alpha:1];
        [self initializeSubViews];
    }
    return self;
}

#pragma mark -- UI --
- (void)initializeSubViews {
    
    self.tipImv = [[UIImageView alloc] init];
    self.tipImv.image = [UIImage imageNamed:@"ICHomePage_marqueeView_tip"];
    
    self.marqueeView = [[UIView alloc] init];
    self.marqueeView.backgroundColor = [UIColor clearColor];
    self.marqueeView.layer.masksToBounds = YES;
    
    self.closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.closeBtn setImage:[UIImage imageNamed:@"ICHomePage_marqueeView_close"] forState:UIControlStateNormal];
    [self.closeBtn addTarget:self action:@selector(closeBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:self.tipImv];
    [self addSubview:self.marqueeView];
    [self addSubview:self.closeBtn];
    
    [self.tipImv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.width.height.mas_equalTo(18);
        make.centerY.equalTo(self.mas_centerY).offset(0);
    }];
    
    [self.marqueeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.tipImv.mas_right).offset(10);
        make.top.bottom.offset(0);
    }];
    
    [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.marqueeView.mas_right).offset(10);
        make.right.offset(-10);
        make.width.height.mas_equalTo(18);
        make.centerY.equalTo(self.mas_centerY).offset(0);
    }];
    
    [self layoutIfNeeded];
    [self.marqueeView addSubview:self.marqueeLb];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(becomeActive) name:@"UIApplicationDidBecomeActiveNotification" object:nil];
}

#pragma mark -- 设置跑马灯内容 --
- (NSTimeInterval)displayDurationForString:(NSString*)string {
    return string.length/3;
}

- (void)setLeftImageStr:(NSString *)leftImageStr {
    
    _leftImageStr = leftImageStr;
    self.tipImv.image = [UIImage imageNamed:leftImageStr];
}

- (void)setRightImageStr:(NSString *)rightImageStr {

    _rightImageStr = rightImageStr;
    [self.closeBtn setImage:[UIImage imageNamed:rightImageStr] forState:UIControlStateNormal];
    if ([rightImageStr isEqualToString:@""] || rightImageStr == nil || [rightImageStr isEqual:[NSNull null]] || rightImageStr == NULL) {
        _closeBtn.hidden = YES;
    }else{
        _closeBtn.hidden = NO;
    }
    
}

#pragma mark -- 点击事件 --
- (void)closeBtnClicked:(UIButton *)button {
    if (self.marqueeViewDismiss) {
        self.marqueeViewDismiss();
    }
}

#pragma mark -- lazy load --
- (UILabel *)marqueeLb {
    if (!_marqueeLb) {
        _marqueeLb = [[UILabel alloc] init];
        _marqueeLb.textColor = [UIColor colorWithRed:0x66/255.0 green:0x66/255.0 blue:0x66/255.0 alpha:1];
        _marqueeLb.font = [UIFont systemFontOfSize:14.0f];
        _marqueeLb.text = _contentString;
        UIFont *fnt = [UIFont systemFontOfSize:14.0f];
        _marqueeLb.font = fnt;
        CGSize msgSize = [_marqueeLb.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
        _marqueeLb.frame = CGRectMake(0, 8, msgSize.width, 20);
    }
    return _marqueeLb;
}

- (void)setContentString:(NSString *)contentString {
    _contentString = contentString;
    [self becomeActive];
}

- (void)becomeActive {
    
    CGSize msgSize = [_contentString sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14.f],NSFontAttributeName, nil]];
    if (msgSize.width > self.marqueeView.frame.size.width) {
        [self backAndRestart];
    }else {
        [self.marqueeLb.layer removeAllAnimations];
        self.marqueeLb.text = _contentString;
        self.marqueeLb.frame = CGRectMake(0, 8, msgSize.width, 20);
    }
}

#pragma mark - 操作
- (void)startAnimation {
    [self moveAction];
}

- (void)backAndRestart {
    
    [self.marqueeLb.layer removeAllAnimations];
    [self.marqueeLb removeFromSuperview];
    self.marqueeLb = nil;
    [self.marqueeView addSubview:self.marqueeLb];
    [self moveAction];
}

- (void)stopAnimation {
    [self pauseLayer:self.marqueeLb.layer];
}

- (void)restartAnimation {
    [self resumeLayer:self.marqueeLb.layer];
}

- (void)moveAction {
    
    CGRect fr = self.marqueeLb.frame;
    fr.origin.x = self.marqueeView.frame.size.width;
    self.marqueeLb.frame = fr;
    
    CGPoint fromPoint = CGPointMake(self.marqueeView.frame.size.width + self.marqueeLb.frame.size.width/2, self.marqueeView.frame.size.height/2);
    
    UIBezierPath *movePath = [UIBezierPath bezierPath];
    [movePath moveToPoint:fromPoint];
    [movePath addLineToPoint:CGPointMake(-self.marqueeLb.frame.size.width/2, self.marqueeView.frame.size.height/2)];
    
    CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    moveAnim.path = movePath.CGPath;
    moveAnim.removedOnCompletion = YES;
    [moveAnim setDelegate:self];
    
    _timeInterval = [self displayDurationForString:_contentString];
    moveAnim.duration = _timeInterval;
    [self.marqueeLb.layer addAnimation:moveAnim forKey:nil];
}

- (void)pauseLayer:(CALayer*)layer {
    
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

- (void)resumeLayer:(CALayer*)layer {
    
    CFTimeInterval pausedTime = layer.timeOffset;
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (flag) {
        [self moveAction];
    }
}

@end
